資料


Posted by mijouhsieh on 2023-04-09

資料我們多半會存在其他地方,也許是資料庫,也許是伺服器主機上,或者從其他資源(例如第三方 API)而來。
很少情況下是直接放在管理路由的 app.js 當中。

透過把資料存成 JSON 檔案,或存放在資料庫中再載入,讓 app.js 這支檔案,可以專門處理路由架構,而不用把一大包資料放在 app.js 中

因此,把外部的資料載入 Express 中,再將讀取到的資料呈現在網頁上。

3 個步驟:

  1. 下載電影清單
  2. 將 JSON 檔案載入 Express 中
  • require() 中,如果放入的是套件的名稱,則 Node.js 會去 node_modules 資料中,找看看是否載得到這個套件;
  • require() 內寫的是路徑時,則 Node.js 會根據你所提供的路徑去找到並載入該檔案。
    const movieList = require('./movies.json')
    透過變數 movieList 取得 movies.json 裡面的資料。
  1. 將外部資料帶入樣板引擎中
    app.get('/', (req, res) => {
    // pass the movie data into 'index' partial template
    res.render('index', { movies: movieList.results })
    })
    

#Data #存資料位置







Related Posts

leetcode-Remove Duplicates from an Array (ES6)

leetcode-Remove Duplicates from an Array (ES6)

CodeBridge 與 DISQUS 留言功能串接

CodeBridge 與 DISQUS 留言功能串接

延遲選擇權於再生能源投資的paper-1

延遲選擇權於再生能源投資的paper-1


Comments